package com.xiaoge.testproxy;

import com.xiaoge.service.UserService;
import com.xiaoge.service.UserServiceImpl;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.Nonnull;

/**
 * TODO
 *
 * @author <a href="mailto:1330137071@qq.com">Zhang Xiao</a>
 * @since
 */
//@Configuration
public class TestProxyFactoryBean {

	/**
	 * 利用FactoryBean机制将代理对象作为一个Bean
	 * @return
	 */
	@Bean
	public ProxyFactoryBean userServiceProxy() {
		UserService userService = new UserServiceImpl();

		ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
		proxyFactoryBean.setTarget(userService);
		proxyFactoryBean.addAdvice(new MethodInterceptor() {
			@Nullable
			@Override
			public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
				System.out.println(".....before.....");
				Object result = invocation.proceed();  // target调用的方法, 例如target.test()
				System.out.println(".....after.....");
				return result;
			}
		});

		return proxyFactoryBean;
	}

}
